package com.fjwt.gz.coupon.wx;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.third.bo.CouponAwardBo;
import com.fjwt.gz.core.third.interfaces.ICheckService;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
@Service
@Slf4j
public class WxCheckBillService implements ICheckService {

    @Autowired
    private WxCouponStocksService wxCouponStocksService;


    @Override
    public JSONObject getBill(CouponAwardBo couponAwardBo) {

        log.info("开始微信对账，卡券数据信息：{}", couponAwardBo);

        if (StringUtils.isBlank(couponAwardBo.getPayConfig())) {
            log.warn("支付配置参数为空");
            return null;
        }

        JSONObject payAuthConfigJson = JSON.parseObject(couponAwardBo.getPayConfig());
        String stockId = payAuthConfigJson.getString("stockid");
        log.info("活动批次号: {}", stockId);
        BufferedReader bufferedReader = authConnect(Integer.valueOf(stockId));
        if (bufferedReader == null) {
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("billData", bufferedReader);
        return jsonObject;
    }


    /**
     * 微信对账直连
     * @param stockId    批次号
     * @return 账单数据流
     */
    private BufferedReader authConnect(Integer stockId) {
        if (stockId == null) {
            log.error("批次号为空，无法拉取账单");
            return null;
        }
        //批次号
//            String stockId = "19647027";
//            String stockId = String.valueOf(couponId);
        try {
            String url = wxCouponStocksService.getStockUseFlow(String.valueOf(stockId));
            if (StrUtil.isBlank(url)) {
                log.error("微信拉取账单数据地址为空，批次号：{}", stockId);
                throw new RuntimeException("微信拉取账单地址为空");
            }
            log.info("微信对账拉取账单数据文件地址：{}", url);
            WxPayService wxPayService = wxCouponStocksService.getWxPayServiceV();
            InputStream inputStream = wxPayService.downloadBill(url);
            if (inputStream == null) {
                log.error("微信下载账单数据流失败，批次号：{}", stockId);
                throw new RuntimeException("微信下载账单数据流失败");
            }
            return new BufferedReader(new InputStreamReader(inputStream));
        } catch (Exception e) {
            log.error("微信对账拉取账单失败，批次号：{}，错误信息：{}", stockId, e.getMessage(), e);
            throw new RuntimeException("微信对账拉取账单失败", e);
        }
    }

}

